package com.leetcode;

import com.leetcode.common.TreeNode;

/**
 * 129. 求根节点到叶节点数字之和
 * 深度优先遍历(自底向上)
 *
 * @author fy
 * @date 2022/4/25 11:35
 */
public class Solution129_2 {

    public int sumNumbers(TreeNode root) {
        return dfs(root, 0);
    }

    private int dfs(TreeNode node, int preSum) {
        if (node == null) {
            return 0;
        }
        int sum = preSum * 10 + node.val;
        if (node.left == null && node.right == null) {
            return sum;
        }
        return dfs(node.left, sum) + dfs(node.right, sum);
    }

}
